import { SendController } from './lib/sendController'                       //发送器
import { ReceiverController } from './lib/receiverController'               //接收器
import Heart from "./lib/heart";                                            //心跳对象
import TalkObject from './lib/talkObject';                                  //会话对象
import FriendObject from './lib/friendObject';                              //好友申请
import Controller from './lib/controller';
import Storage from './lib/storage';

let config = null;

export class Socket {
    static instance = null;                                                 // 实例
    static v = 27;
    port = 2345;
    constructor() {
        if (!Socket.instance) {
            Socket.instance = this;
            Socket.instance.so = null;
            //页面刷新载入本地缓存
            this.loginData = { ...this.loginData, ...config };
            let userData = sessionStorage.getItem('userData');
            let initConfig = sessionStorage.getItem('config');
            if(initConfig){
                config = JSON.parse(initConfig)
            }
            if (userData) {
                userData = JSON.parse(userData);
                this.loginData.userData = { ...userData }
            }
            //实例化发送器和接受器、会话对象、心跳
            this.sendController = new SendController(this);                      //socket 成功连接时，实例化发送器实例
            this.receiverController = new ReceiverController(this);              //接收器
            this.talkObject = new TalkObject();
            this.controller = new Controller(this, config);
            this.friendObject = new FriendObject();
            this.heart = new Heart();        
            this.storage = new Storage(this);  
            let loginData = sessionStorage.getItem('loginData');                 //当本地token,key 进行快速登录
            if (loginData) {
                loginData = JSON.parse(loginData);
                let { token, key, member_id, port } = loginData;
                if (token && key && member_id && port) {this.action("quickConnect",loginData,() => {},() => {});}
            }
            console.log(this.controller,11)
            this.UserTalkList = [];
            // new Error("版本:" + Socket.v).message
            console.log("版本:" + Socket.v)
            // throw "版本:" + Socket.v;
        }
        return Socket.instance;
    }
    /*用户操作方法入口*/
    action(fnName, params, callback, failCallback) {
        return this.controller.action(fnName, params, callback, failCallback)
    }
}